import axios from 'axios'
import { serialize } from '../utils/util'

// 默认超时时间
axios.defaults.timeout = 10000

// 跨域请求，允许保存cookie
axios.defaults.withCredentials = false
// NProgress 配置
NProgress.configure({
  showSpinner: false
})

// http request拦截
axios.interceptors.request.use(
  (config) => {
    // 开启 progress bar
    NProgress.start()
    const meta = config.meta || {}

    // headers中配置text请求
    if (config.text === true) {
      config.headers['Content-Type'] = 'text/plain'
    }
    // headers中配置serialize为true开启序列化
    if (config.method === 'post' && meta.isSerialize === true) {
      config.data = serialize(config.data)
    }
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)
// http response 拦截
axios.interceptors.response.use(
  (res) => {
    // 关闭 progress bar
    NProgress.done()
    // 获取状态码
    const status = res.data.code || res.status || res.code
    const statusWhiteList = website.statusWhiteList || []
    let message // = res.data.msg || res.data.error_description || '请重新登录';
    if (statusWhiteList.includes(status)) return Promise.reject(res)
    if (status !== 200) {
      if (status === 401 || status === 460) {
        return null
      } else {
        if (res.config.noNormalReject) {
          return res
        }
        message = res.data.msg || '服务内部错误'
      }
      const ignoreMsg = res.config.ignoreMsg
      return Promise.reject(new Error(message))
    }
    return res
  },
  (error) => {
    NProgress.done()
    const statusWhiteList = website.statusWhiteList || []
    // 如果在白名单里则自行catch逻辑处理
    if (statusWhiteList.includes(error.data.code)) {
      return Promise.reject(error)
    }
    return Promise.reject(new Error(error))
  }
)

export default axios
